<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="设备编号" prop="deviceNumber">
        <el-input
          v-model="queryParams.deviceNumber"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="小屋" prop="lovehouseId">
        <el-cascader
          v-model="queryParams.lovehouseId"
          :options="schoolList"
          :props="{
            value: 'value',
            label: 'label',
            children: 'children',
            emitPath: false,
          }"
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in vm_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:vm:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="vmList">
      <el-table-column
        label="序号"
        align="center"
        prop="id"
        type="index"
        width="55px"
      />
      <el-table-column label="设备编号" align="center" prop="deviceNumber" />
      <el-table-column label="设备图片" align="center" prop="image" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="小屋" align="center" prop="lovehouse.houseName" />
      <el-table-column label="行数" align="center" prop="numRows" />
      <el-table-column label="列数" align="center" prop="numCols" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{m}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            type="primary"
            @click="handleGoods(scope.row)"
            v-hasPermi="['manage:vm:list']"
            >货架</el-button
          >
          <el-button
            :type="scope.row.status == 0 ? 'success' : 'danger'"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:vm:edit']"
            >{{ scope.row.status == 0 ? "启用" : "禁用" }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="vmRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备编号" prop="deviceNumber">
          <el-input
            v-model="form.deviceNumber"
            placeholder="由系统自动生成"
            disabled
          />
        </el-form-item>
        <el-form-item label="设备图片" prop="image">
          <image-upload v-model="form.image" />
        </el-form-item>
        <el-form-item label="行数" prop="numRows">
          <el-input-number
            min="1"
            max="100"
            step="1"
            v-model="form.numRows"
            placeholder="行数"
            :disabled="form.id != null"
          />
        </el-form-item>
        <el-form-item label="列数" prop="numCols">
          <el-input-number
            min="1"
            max="100"
            step="1"
            v-model="form.numCols"
            placeholder="列数"
            :disabled="form.id != null"
          />
        </el-form-item>
        <el-form-item label="小屋" prop="lovehouseId">
        <el-cascader
          v-model="form.lovehouseId"
          :options="schoolList"
          :props="{
            value: 'value',
            label: 'label',
            children: 'children',
            emitPath: false,
          }"
          clearable
        ></el-cascader>
      </el-form-item>
        <el-form-item label="状态" prop="status" v-if="form.id != null">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in vm_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 货道详情对话框 -->
    <GoodShelvesDialog
      :goodVisible="goodVisible"
      :goodData="goodData"
      @handleCloseGood="handleCloseGood"
    ></GoodShelvesDialog>
  </div>
</template>

<script setup name="Vm">
import { listVm, getVm, delVm, addVm, updateVm } from "@/api/manage/vm";
import { voListSchool } from "@/api/manage/school";



const { proxy } = getCurrentInstance();
const { vm_status } = proxy.useDict("vm_status");

const vmList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    lovehouseId: null,
    deviceNumber: null,
    status: null,
  },
  rules: {
    image: [{ required: true, message: "设备图片不能为空", trigger: "blur" }],
    numRows: [{ required: true, message: "行数不能为空", trigger: "blur" }],
    numCols: [{ required: true, message: "列数不能为空", trigger: "blur" }],
    /* qrCode: [{ required: true, message: "二维码不能为空", trigger: "blur" }], */
    lovehouseId: [
      { required: true, message: "请选择小屋", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);
/**货架详情 *********************************************/
import GoodShelvesDialog from "./components/GoodShelvesDialog.vue";
const goodVisible = ref(false);
const goodData = ref({});
// 打开货架弹层
const handleGoods = (row) => {
  goodVisible.value = true;
  goodData.value = row;
};
//关闭货架
const handleCloseGood = () => {
  goodVisible.value = false;
};
/* ************************************************************** */
/** 查询设备列表 */
function getList() {
  loading.value = true;
  listVm(queryParams.value).then((response) => {
    vmList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
/**获取学校级联列表 */
const schoolList = ref([]);
function getSchoolList() {
  voListSchool().then((response) => {
    const filteredRows = response.rows.filter(
      (item) =>
        Array.isArray(item.lovehouseList) && item.lovehouseList.length > 0
    );
    filteredRows.forEach((item) => {
      schoolList.value.push({
        value: item.id,
        label: item.schoolName,
        children: item.lovehouseList.map((lovehouse) => {
          return {
            value: lovehouse.id,
            label: lovehouse.houseName,
          };
        }),
      });
    });
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    lovehouseId: null,
    deviceNumber: null,
    image: null,
    numRows: null,
    numCols: null,
    qrCode: null,
    status: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
  };
  proxy.resetForm("vmRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  /* 确认提示框 */
  proxy.$modal
    .confirm("是否" + row.status == 1 ? "禁用" : "启用" + "设备吗？")
    .then(function () {
      reset();
      form.value.id = row.id
      form.value.status = row.status == 0 ? 1 : 0;
      updateVm(form.value).then((response) => {
          proxy.$modal.msgSuccess(
            form.value.status == 0 ? "禁用成功" : "启用成功"
          );
          getList();
        });
    });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["vmRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateVm(form.value).then((response) => {
          proxy.$modal.msgSuccess(
            form.value.status == 0 ? "禁用成功" : "启用成功"
          );
          open.value = false;
          getList();
        });
      } else {
        addVm(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除设备编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delVm(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "manage/vm/export",
    {
      ...queryParams.value,
    },
    `vm_${new Date().getTime()}.xlsx`
  );
}
getSchoolList();
getList();
</script>
